package com.example.authority.controller;

import cn.hutool.core.map.MapUtil;
import com.example.authority.common.utils.SecurityUtils;
import com.example.authority.domain.User;
import com.example.authority.common.entity.MyConst;
import com.example.authority.common.entity.Result;
import com.example.authority.domain.model.LoginUser;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

@Slf4j
@RestController
public class AuthController extends BaseController{

    /**
     * 图片验证码
     */
    @GetMapping("/captcha")

    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = producer.createText();
        String key = UUID.randomUUID().toString();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        String str = "";
        String base64Img = (str + Base64.getEncoder().encodeToString(outputStream.toByteArray()));
        // 存储到redis中
        redisUtil.hset(MyConst.CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);
        return Result.succ(
                MapUtil.builder()
                        .put("token", key)
                        .put("base64Img", base64Img)
                        .build()
        );
    }
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/test")
    public Result test(){
        return Result.succ("test");
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        log.info("注册用户信息: {}", user);
        try {
            userService.register(user);
        }catch (Exception e) {
            return Result.fail(e.getMessage());
        }
        return Result.succ("register");
    }
    @PreAuthorize("hasRole('normal')")
    @GetMapping("/userInfo")
    public Result userInfo(){
        LoginUser loginUser= SecurityUtils.getCurrentUser();
        User user = loginUser.getUser();
        return Result.succ(user);
    }

}